package cluster

import (
	"fmt"
	"math/rand"
	"net"
	"strconv"
	"time"
)

type Node struct {
	Id    int
	Ip    string
	Port  string
	index map[string]string
}

const (
	LOCALHOST = "127.0.0.1"
)

func (node *Node) ToString() string {
	return "Node " + strconv.Itoa(node.Id) + " : {" + "ip : " + node.Ip + ", port : " + node.Port + "}\n"
}

func NewNode(port string) *Node {
	return &Node{
		Id:   rand.Int(),
		Ip:   LOCALHOST,
		Port: port,
	}
}

func (n *Node) ConnectWithNode(node *Node) bool {
	_, err := net.DialTimeout("tcp", node.Ip+":"+node.Port, time.Duration(10)*time.Second)
	if err != nil {
		fmt.Println("连接失败.")
		return false
	} else {
		fmt.Println("连接成功.")
		return true
	}
	return false

}

func (n *Node) Listen() {
	ln, _ := net.Listen("tcp", ":"+n.Port)
	for {
		conn, err := ln.Accept()
		if err != nil {

		} else {
			fmt.Println("接收到请求.")
			conn.Close()
		}
	}
}
